package com.ecreditpal.audio.platform.ali;

import com.alibaba.fastjson.JSON;
import com.alibaba.idst.nls.realtime.event.NlsEvent;
import com.alibaba.idst.nls.realtime.event.NlsListener;
import com.alibaba.idst.nls.realtime.protocol.NlsResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lifeng
 * @version 1.0 on 2018/6/19.
 */
@Slf4j
public class RealTimeListener implements NlsListener {
    private String finalResult;

    @Override
    public void onMessageReceived(NlsEvent e) {
        NlsResponse response = e.getResponse();
        response.getFinish();
        if (response.result != null) {
            log.debug("status code = {},get finish is {},get recognize result: {}", response.getText(),response.getFinish(), response.getResult());
            if ("0".equals(response.getFinish())) {
                finalResult  = response.getResult().getText();
            }

            if (response.getQuality() != null) {
                log.info("Sentence {} is over. Get ended sentence recognize result: {}, voice quality is {}",
                        response.result.getSentence_id(), response.getResult(),
                        JSON.toJSONString(response.getQuality()));
            }
        } else {
            log.info(JSON.toJSONString(response));
        }
    }

    @Override
    public void onOperationFailed(NlsEvent e) {
        log.error("status code is {}, on operation failed: {}", e.getResponse().getStatusCode(),
                e.getErrorMessage());

    }

    @Override
    public void onChannelClosed(NlsEvent e) {
        NlsResponse response = e.getResponse();
        log.debug("on websocket closed.");
        System.out.println(123);
    }


    public String getFinalResult() {
        return finalResult;
    }
}
